package com.aiju.utils;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.View;

import com.aiju.base.activity.AbsActivity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AppUtil {

	public static AbsActivity currentActivity;
	public static AbsActivity mainActivity;

	private static final BitmapFactory.Options OPTS = new BitmapFactory.Options();

	static {
		OPTS.inPreferredConfig = Bitmap.Config.RGB_565;
	}

	public static String escapeBrace(String braceIncluded) {
		if (!TextUtils.isEmpty(braceIncluded)) {
			return braceIncluded.replaceAll("[{}]", "");
		}
		return "";
	}

	public static String truncation(String string, int length) {
		if (!TextUtils.isEmpty(string)) {
			return (string.length() <= length ? string : string.substring(0,
					length - 1) + "...");
		}
		return "";
	}

	public static Object get(Object one, String name, Class<?>... c) {
		try {
			Field f = getField(one, name, c);
			return f.get(one);
		} catch (Exception e) {

		}
		return null;
	}

	public static int getBackgroundResource(View v) {
		return (Integer) get(v, "mBackgroundResource");
	}

	public static Bitmap getBitmapFromApp(PackageManager pm,
			PackageInfo packInfo) {
		BitmapDrawable drawable = (BitmapDrawable) packInfo.applicationInfo
				.loadIcon(pm);
		return drawable.getBitmap();
	}

	public static Bitmap getBitmapFromApp(PackageManager pm, String packageName)
			throws NameNotFoundException {
		if (pm == null || packageName == null) {
			return null;
		}

		PackageInfo pi = pm.getPackageInfo(packageName, 0);
		if (pi == null) {
			return null;
		}
		BitmapDrawable drawable = (BitmapDrawable) pi.applicationInfo
				.loadIcon(pm);
		return drawable.getBitmap();
	}

	public static Field getField(Object one, String name, Class<?>... c)
			throws Exception {
		Field f = null;
		if (null == c || 0 == c.length) {
			f = one.getClass().getDeclaredField(name);
		} else {
			f = c[0].getDeclaredField(name);
		}
		f.setAccessible(true);
		return f;
	}

	public static Method getMethod(String name, Class<?> which, Class<?>... c) {
		try {
			Method m = which.getMethod(name, c);
			m.setAccessible(true);
			return m;
		} catch (Exception e) {
			// LogException.setLog(e, "getMethod=" + name);
			return null;
		}
	}

}
